from datetime import datetime

from fastapi import Request
from sqlalchemy.orm import Session

from core.dao.cms_car_track_dao import CmsCarTrackDao
from core.dao.cms_gaode_trace_dao import CmsGaodeTraceDao
from core.entity.vo.common import CrudResponse
from core.entity.vo.view_models import CmsCarTrackVO, CmsGaodeTraceVO
from core.service.gaode.gaode_point_service import GaodePointService
from core.service.gaode.gaode_trace_service import GaodeTraceService
from utils.uuid import UUID


class CmsCarTrackService:
    """
    高德终端service
    """

    @classmethod
    def get_cms_car_track_by_id(cls, result_db: Session, id: int):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param id: id
        :return: 参数配置列表信息对象
        """
        cms_car_track = CmsCarTrackDao.get_cms_car_track_by_id(result_db, id)

        return cms_car_track

    @classmethod
    def get_cms_car_track_by_track_id(cls, result_db: Session, track_id: str):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param track_id: 高德终端id
        :return: 参数配置列表信息对象
        """
        cms_car_track = CmsCarTrackDao.get_cms_car_track_by_track_id(result_db, track_id)

        return cms_car_track

    @classmethod
    def get_cms_car_track_by_gaode_track_id(cls, result_db: Session, gaode_track_id: str):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param gaode_track_id: 高德终端id
        :return: 参数配置列表信息对象
        """
        cms_car_track_list = CmsCarTrackDao.get_cms_car_track_by_gaode_track_id(result_db, gaode_track_id)

        return cms_car_track_list

    @classmethod
    def get_cms_car_track_by_car_number(cls, result_db: Session, gaode_track_id: str, begin_time: datetime,
                                        end_time: datetime):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param gaode_track_id: 高德终端id
        :param begin_time: 开始时间
        :param end_time: 结束时间
        :return: 参数配置列表信息对象
        """
        cms_car_track_list = CmsCarTrackDao.get_cms_car_track_by_car_number(result_db, gaode_track_id, begin_time,
                                                                            end_time)

        return cms_car_track_list

    @classmethod
    def get_cms_car_track_like_name(cls, result_db: Session, trace_name: str):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param query_object: 查询参数对象
        :return: 参数配置列表信息对象
        """
        cms_car_track_list = CmsCarTrackDao.get_cms_car_track_like_name(result_db, trace_name)

        return cms_car_track_list

    @classmethod
    def add_cms_car_track(cls, result_db: Session, cms_car_track: CmsCarTrackVO):
        """
        新增参数配置信息service
        :param request: Request对象
        :param result_db: orm对象
        :param cms_car_track: 新增参数配置对象
        :return: 新增参数配置校验结果
        """
        # 根据轨迹名称判断轨迹是否创建
        gaode_trace = CmsGaodeTraceDao.get_cms_gaode_trace_by_name(result_db, cms_car_track.execute_id)
        if gaode_trace is None:
            # 创建高德轨迹
            result = GaodeTraceService.add_track(cms_car_track.service_id, cms_car_track.terminal_id,
                                                 cms_car_track.track_name)
            if result['errcode'] == 10000:
                print("高德轨迹创建成功" + str(result))
                gaode_track_id = result['data']['trid']
                vo = CmsGaodeTraceVO()
                vo.id = int(UUID().uuid())
                vo.service_id = cms_car_track.service_id
                vo.terminal_id = cms_car_track.terminal_id
                vo.trace_id = gaode_track_id
                vo.trace_name = cms_car_track.execute_id
                vo.state = 1
                vo.execute_id = cms_car_track.execute_id
                CmsGaodeTraceDao.add_cms_gaode_trace_dao(result_db, vo)
                result_db.commit()
            else:
                print("高德轨迹创建失败" + str(result))
                result = dict(is_success=False, message="高德轨迹创建失败" + str(result['errmsg']))
                return CrudResponse(**result)
        else:
            gaode_track_id = gaode_trace.trace_id

        # 组装轨迹节点信息
        points = []
        point = dict(location=cms_car_track.lon + "," + cms_car_track.lat, height=cms_car_track.height,
                     speed=cms_car_track.speed, direction=cms_car_track.direction,
                     locatetime=round(cms_car_track.record_time.timestamp() * 1000))
        points.append(point)
        print(points)
        # 调用上传轨迹节点接口
        result = GaodePointService.upload_point(cms_car_track.service_id, cms_car_track.terminal_id,
                                                gaode_track_id, points)
        if result['errcode'] == 10000:
            try:
                print("高德轨迹节点上传成功" + str(result))
                cms_car_track.gaode_track_id = gaode_track_id
                # 插入车辆轨迹信息
                CmsCarTrackDao.add_cms_car_track_dao(result_db, cms_car_track)
                result_db.commit()
                result = dict(is_success=True, message='新增成功')
            except Exception as e:
                print("高德轨迹节点上传失败" + str(e))
                result_db.rollback()
                result = dict(is_success=False, message=str(e))
        else:
            result = dict(is_success=False, message=str(result['errmsg']))
        return CrudResponse(**result)

    @classmethod
    def delete_cms_car_track(cls, result_db: Session, id: int, service_id: str, terminal_id: str, gaode_track_id: str):
        """
        删除菜单信息service
        :param result_db: orm对象
        :param id: id
        :param service_id: 服务编码
        :param terminal_id: 终端编码
        :param gaode_track_id: 轨迹编码
        :return: 删除终端
        """
        if id > 0:
            result = GaodeTraceService.delete_track(service_id, terminal_id, gaode_track_id)
            if result['errcode'] == 10000:
                try:
                    print("高德轨迹删除成功" + str(result))
                    # 删除车辆轨迹
                    CmsCarTrackDao.delete_by_trace_id_dao(result_db, gaode_track_id)
                    result_db.commit()
                    result = dict(is_success=True, message='删除成功')
                except Exception as e:
                    result_db.rollback()
                    result = dict(is_success=False, message=str(e))
            else:
                result = dict(is_success=False, message=str(result['errmsg']))
        else:
            result = dict(is_success=False, message='传入高德终端id为空')
        return CrudResponse(**result)
